package com.github.base.utils;

import cn.hutool.core.util.StrUtil;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import lombok.SneakyThrows;

import java.io.FileReader;
import java.io.FileWriter;

public class FileUtil {

    @SneakyThrows
    public static String splitCsv(String filePath, Integer rowsPerFile, String outputFilePrefix) {
        if (rowsPerFile == null) {
            rowsPerFile = 10000;
        }
        if (StrUtil.isBlank(outputFilePrefix)) {
            outputFilePrefix = "/Users/jzy/Desktop/csv/output_file_";
        }
        try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
            String[] line;
            int fileCounter = 0;
            int rowCount = 0;
            CSVWriter writer = null;

            while ((line = reader.readNext()) != null) {
                if (rowCount % rowsPerFile == 0) {
                    if (writer != null) {
                        writer.close();
                    }
                    fileCounter++;
                    String outputFilePath = outputFilePrefix + fileCounter + ".csv";
                    writer = new CSVWriter(new FileWriter(outputFilePath));
                    if (rowCount == 0) {
                        writer.writeNext(line);
                    }
                }
                writer.writeNext(line);
                rowCount++;
            }

            if (writer != null) {
                writer.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
